import time

from appium import webdriver
from config.config import APP_CONFIG, APPIUM_SERVER
import logging

logger = logging.getLogger(__name__)


class DriverManager:
    _driver = None

    @classmethod
    def get_driver(cls):
        if cls._driver is None:
            try:
                cls._driver = webdriver.Remote(
                    f"http://{APPIUM_SERVER['host']}:{APPIUM_SERVER['port']}/wd/hub",
                    APP_CONFIG
                )
                logger.info("Appium驱动初始化成功")
            except Exception as e:
                logger.error(f"Appium驱动初始化失败: {e}")
                raise
        else:
            # driver 已存在，只冷启动 App
            time.sleep(3)
            cls._driver.activate_app('com.topboya.linker')

        return cls._driver

    @classmethod
    def quit_driver(cls):
        if cls._driver:
            cls._driver.quit()
            cls._driver = None
            logger.info("Appium驱动已关闭")